<?php
class Admin_HotelController extends Apps_Controller_Action_Admin {

	//LIST
	public function indexAction() {
		$this->actResolve('act_delete',
						  'delete', null, null, array('id' => $this->_getParam('item_checker')),
					 	  true);

		$tbHotel = new M_DbTable_Hotel();
		$grid 	= new Apps_Plugin_Grid('hotelGrid');

		$grid->setData($tbHotel->getList())
			 ->setTableCaption('Hotel & Resort')
			 ->setTableColumnFormat(array(
			 		array('title'		=> 'ID',
			 			  'dataField'	=> 'id',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Name',
			 			  'dataField'   => 'en_name'),
			 		array('title'		=> 'Type',
			 			  'dataField'	=> 'hotel_type_en_title',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Phone',
			 			  'dataField'	=> 'phone',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Email',
			 			  'dataField'	=> 'email',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Address',
			 			  'dataField'	=> 'en_address',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Best Selling',
			 			  'html'	    => function ($rs) {
			 			  						return ($rs['best_selling'] == M_DbTable_Hotel::BEST_SELLING_TRUE)?
			 			  						'<a href="##" class="ajax-link-must-confirm popup hint  label label-success" data-ajax-to="/admin/hotel/change-value?p=sell&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="No">Yes</a>' :
			 			  						'<a href="##" class="ajax-link-must-confirm popup hint  label label-warning" data-ajax-to="/admin/hotel/change-value?p=sell&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="Yes">No</a>';
											},
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Promotion',
			 			  'html'	    => function ($rs) {
			 			  						return ($rs['special_offer'] == M_DbTable_Hotel::SPECIAL_OFFER_TRUE)?
			 			  						'<a href="##" class="ajax-link-must-confirm popup hint  label label-success" data-ajax-to="/admin/hotel/change-value?p=offer&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="No">Yes</a>' :
			 			  						'<a href="##" class="ajax-link-must-confirm popup hint  label label-warning" data-ajax-to="/admin/hotel/change-value?p=offer&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="Yes">No</a>';
											},
			 			  'class'		=> 'center'),
                    array('title'		=> 'Public',
			 			  'html'	    => function ($rs) {
			 			  						return ($rs['status'] == M_DbTable_Hotel::STATUS_ACTIVE)?
			 			  						'<a href="##" class="ajax-link-must-confirm popup hint  label label-success" data-ajax-to="/admin/hotel/change-value?p=public&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="No">Yes</a>' :
			 			  						'<a href="##" class="ajax-link-must-confirm popup hint  label label-warning" data-ajax-to="/admin/hotel/change-value?p=public&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="Yes">No</a>';
											},
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Photo',
			 			  'width'       => '2%',
			 			  'html'        => array('<a href="/admin/photo-management/hotel?id=%s"><i class="icon-folder-open" title="Quản lý ảnh"></i></a>',
			 			  				   array('id')),
			 			  'class'		=> 'center'),
	 			    array('title'		=> 'View',
	 			  		  'html'        => array('<a href="/hotel/detail?id=%s" target="_blank"><i class="icon-list-alt"></i></a>',
	 			  							array('id')),
	 			  		  'class'		=> 'center'),
			 		array('title'       => 'Edit',
			 			  'html'        => array('<a href="/admin/hotel/edit?id=%s"><i class="icon-edit" title="Sửa"></i></a>',
			 			  				   array('id')),
			 			  'width'       => '2%',
	 			  		  'class'		=> 'center'),
			 		array('title'       => 'Delete',
			 			  'html'        => array('<a href="/admin/hotel/delete?id=%s" class="must-confirm" data-must-confirm-msg="Bạn có chắc là muốn xóa?"><i class="icon-remove" title="Xóa"></i></a>',
			 			  				   array('id')),
			 			  'width'       => '2%',
	 			  		  'class'		=> 'center')
			 		));
		$grid->applySearch(new Admin_Form_Search_Hotel());

		$this->view->grid = $grid;
	}
	//ADD
	public function addAction() {
		$rq 		= $this->_request;
		$f 			= new Admin_Form_AddHotel();
		$tbHotel	= new M_DbTable_Hotel();
		$tbArticle 	= new M_DbTable_Article();

		if ($rq->isPost()) {
			if ($f->isValid($rq->getParams())) {
				// Upload thumbnail
				$uploader = new Apps_Plugin_Upload_File();
				$uploader->setMaxQuantity(1)
						 ->setSubCategory(Apps_Plugin_Upload_File::CAT_HOTEL);
				$avatar = ($uploaded = $uploader->upload())
						 	 ? $uploaded['avatar']['uri']
						 	 : null;
				$thumbnail = ($uploaded = $uploader->upload())
						 	 ? $uploaded['thumbnail']['uri']
						 	 : null;

				//resize images
				try {
				    $image = new Apps_Plugin_ResizeImages();
				    $image->load(PUBLIC_PATH .$thumbnail);
				    $image->resizeToWidth(156);
				    $image->save(PUBLIC_PATH .$thumbnail);
				} catch (Exception $e) {
				    //Excetion here
				}

				$data = $f->getValues();
				$data['avatar']    = $avatar;
				$data['thumbnail'] = $thumbnail;
				$data['region_id'] = $rq->getParam('region_id');

				$keyFilterHotel = array('hotel_type_id',
									    'region_id',
									    'name',
									    'en_name',
										'phone',
										'hotline',
										'fax',
									  	'email',
									    'address',
									    'en_address',
									    'rating',
									    'best_selling',
									    'special_offer',
									    'phone',
									    'meta_keyword',
									    'meta_description',
									    'header_title',
									    'avatar');

				$hotelId = $tbHotel->safelyInsert($data, $keyFilterHotel);

				if ($hotelId) {
				    //add price hotel
				    $tbHotelPrice  = new M_DbTable_HotelPrice();
				    $roomCatalogy  = $rq->getParam('room_catalogy');
				    $singlePrice   = $rq->getParam('single');
				    $doublePrice   = $rq->getParam('double');
				    $extraBedPrice = $rq->getParam('extra-bed');
				    $validityStartList  = $rq->getParam('validity_start');
				    $validityEndList    = $rq->getParam('validity_end');

				    foreach($roomCatalogy as $k => $v) {
				        if($v) {
				            if($validityStartList[$k] && Zend_Date::isDate($validityStartList[$k])) {
            				    $validityStartOject  = new Zend_Date($validityStartList[$k], 'dd/MM/yyyy');
				                $validityStart       = $validityStartOject->toString('yyyy-MM-dd');
				            } else {
				                $validityStart = null;
				            }
				            if($validityEndList[$k] && Zend_Date::isDate($validityEndList[$k])) {
        				        $validityEndOject = new Zend_Date($validityEndList[$k], 'dd/MM/yyyy');
                                $validityEnd      = $validityEndOject->toString('yyyy-MM-dd');
				            } else {
				                $validityEnd = null;
				            }

				            $hotelPrice    = array('hotel_id'      => $hotelId,
            				                       'room_catalogy' => $v,
                				                   'single'        => $singlePrice[$k],
                				                   'double'        => $doublePrice[$k],
                				                   'extra-bed'     => $extraBedPrice[$k],
                				                   'validity_start' => $validityStart,
                				                   'validity_end'   => $validityEnd);
				            $tourHotelId = $tbHotelPrice->insert($hotelPrice);
				        }
				    }

					$this->_flashMessenger->addMessage(
						$tbArticle->addArticle($data, $hotelId, $tbArticle::REFERENCE_TYPE_HOTEL)
						? self::$msgAddSuccess
						: self::$msgAddFailed
					);
				}

				$this->_helper->redirector('index', null, null);
			}
		}
		$this->view->form = $f;
	}

	//EDIT Hotel
	public function editAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');

		$tbHotelPrice  = new M_DbTable_HotelPrice();
		$tbHotel       = new M_DbTable_Hotel();
		$f             = new Admin_Form_AddHotel();

		$hotel 	= $tbHotel->getHotel($id);
		if (!$id || !$hotel) {
			$this->_helper->redirector('index');
		}

		if ($rq->isPost()) {
			if ($f->isValid($rq->getParams())) {
				$tbArticle 	= new M_DbTable_Article();

				// Upload thumbnail - replace thumbnail if changed
				$rs = $tbArticle->getArticleByReference($id, $tbArticle::REFERENCE_TYPE_HOTEL)->query()->fetch();
				$thumbnail = $rs['thumbnail'];

				if(Apps_Plugin_Upload_File::isUploaded('thumbnail')) {
					$uploader = new Apps_Plugin_Upload_File();
					$uploader->setMaxQuantity(1)
							 ->setSubCategory(Apps_Plugin_Upload_File::CAT_HOTEL);

					$uploaded = $uploader->upload();
					if($uploaded) {
						unlink(Apps_Plugin_Upload_File::getPath($thumbnail)); // Delete ex-thumbnail
						$thumbnail = $uploaded['thumbnail']['uri'];
						//resize images
						try {
						    $image = new Apps_Plugin_ResizeImages();
						    $image->load(PUBLIC_PATH .$thumbnail);
						    $image->resizeToWidth(156);
						    $image->save(PUBLIC_PATH .$thumbnail);
						} catch (Exception $e) {
						    //Excetion here
						}
					}
				}

				$data = $f->getValues();
				$data['thumbnail'] = $thumbnail;

				$keyFilterHotel = array('hotel_style_id',
									    'region_id',
									    'name',
									    'en_name',
										'phone',
										'hotline',
										'fax',
									  	'email',
									    'address',
									    'en_address',
									    'rating',
									    'best_selling',
									    'special_offer',
									    'meta_keyword',
									    'meta_description',
									    'header_title',
									    'phone');

				$rT = $tbHotel->safelyUpdate($data, array('id =?' => $id) , $keyFilterHotel);
				$rA = $tbArticle->updateArticle($data, $id, $tbArticle::REFERENCE_TYPE_HOTEL);

				//edit price: delete then add new
			    $tbHotelPrice->delete(array('hotel_id =?' => $id));

			    $roomCatalogy  = $rq->getParam('room_catalogy');
			    $singlePrice   = $rq->getParam('single');
			    $doublePrice   = $rq->getParam('double');
			    $extraBedPrice = $rq->getParam('extra-bed');
			    $validityStartList  = $rq->getParam('validity_start');
			    $validityEndList    = $rq->getParam('validity_end');

			    foreach($roomCatalogy as $k => $v) {
			        if($v) {
    			        if($validityStartList[$k] != '' && Zend_Date::isDate($validityStartList[$k], 'dd/MM/yyyy')) {
        				    $validityStartOject  = new Zend_Date($validityStartList[$k], 'dd/MM/yyyy');
			                $validityStart       = $validityStartOject->toString('yyyy-MM-dd');
			            } else {
			                $validityStart = '';
			            }
			            if($validityEndList[$k] != '' && Zend_Date::isDate($validityEndList[$k], 'dd/MM/yyyy')) {
    				        $validityEndOject = new Zend_Date($validityEndList[$k], 'dd/MM/yyyy');
                            $validityEnd      = $validityEndOject->toString('yyyy-MM-dd');
			            } else {
			                $validityEnd = '';
			            }

			            $hotelPrice    = array('hotel_id'      => $id,
        				                       'room_catalogy' => $v,
            				                   'single'        => $singlePrice[$k],
            				                   'double'        => $doublePrice[$k],
            				                   'extra-bed'     => $extraBedPrice[$k],
            				                   'validity_start' => $validityStart,
            				                   'validity_end'   => $validityEnd);
			            $tourHotelId = $tbHotelPrice->insert($hotelPrice);
			        }
			    }
				if (!$rT && !$rA) {
					$this->_flashMessenger->addMessage(self::$msgUpdateFailed);
				} else {
					$this->_flashMessenger->addMessage(self::$msgUpdateSuccess);
				}
				$this->_helper->redirector('index');
			}
		}
        $hotelPrice = $tbHotelPrice->fetchAll(array('hotel_id =?' => $id))->toArray();
        $this->view->hotelPrice = $hotelPrice;

        //Zend_Debug::dump($hotel->query()->fetch());die();
        
		$f->setLegend('Edit Hotel & Resort');
		$f->populate($hotel->query()->fetch());
		$this->view->form = $f;
		$this->render('add');
	}

	//DELETE
	public function deleteAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');

		if (!$id) {
			$this->_helper->redirector('index');
		}

		$tbHotel = new M_DbTable_Hotel();
		$tbArticle = new M_DbTable_Article();

		if (is_numeric($id)) {
			if ($tbHotel->safelyDelete('id ='. $id)) {
				$this->_flashMessenger->addMessage(
					$tbArticle->deleteArticle($id, $tbArticle::REFERENCE_TYPE_HOTEL)
					? self::$msgDeleteSuccess
					: self::$msgDeleteError
				);
			}
		} elseif (is_array($id)) {
			foreach ($id as $v) {
				if ($tbHotel->safelyDelete('id ='. $v)) {
					$tbArticle->deleteArticle($v, $tbArticle::REFERENCE_TYPE_HOTEL);
				}
			}
		}

		$this->_helper->redirector('index');
	}

	public function changeValueAction() {
		$this->disableLayout(true, true);
		$rq = $this->_request;
		$param  = $rq->getParam('p');
		$id 	= intval($rq->getParam('id'));
		$tbHotel = new M_DbTable_Hotel();
		if(!($r = $tbHotel->fetchRow(array('id = ?' => $id))->toArray())) {
			echo '<script>window.location=window.location</script>
				<a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
				. $this->getBacktrackUrl()
				. '">Update Error (Record not found), please wait ...</a>';
		}

		switch ($param) {
			case 'sell':
				($r['best_selling'] == M_DbTable_Hotel::BEST_SELLING_TRUE) ?
					$tbHotel->safelyUpdate(array('best_selling' 	=> M_DbTable_Hotel::BEST_SELLING_FALSE),
										   array('id =?'			=> $id)) :
					$tbHotel->safelyUpdate(array('best_selling' 	=> M_DbTable_Hotel::BEST_SELLING_TRUE),
										   array('id =?'			=> $id));
				break;
			case 'offer':
				($r['special_offer'] == M_DbTable_Hotel::SPECIAL_OFFER_TRUE) ?
					$tbHotel->safelyUpdate(array('special_offer' 		=> M_DbTable_Hotel::SPECIAL_OFFER_FALSE),
										   array('id =?'				=> $id)) :
					$tbHotel->safelyUpdate(array('special_offer' 		=> M_DbTable_Hotel::SPECIAL_OFFER_TRUE),
										   array('id =?'				=> $id));
				break;
			case 'public':
			    ($r['status'] == M_DbTable_Hotel::STATUS_ACTIVE) ?
    			    $tbHotel->safelyUpdate(array('status'  => M_DbTable_Hotel::STATUS_INACTIVE),
                        			     array('id =?'	  => $id)) :
    			    $tbHotel->safelyUpdate(array('status'  => M_DbTable_Hotel::STATUS_ACTIVE),
    			                         array('id =?'  => $id));
			    break;


			default: break;
		}

		echo '<script>location.href = location.href</script>
			<a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
			. $this->getBacktrackUrl()
			. '">Update successfully, please wait ...</a>';
	}

}